package com.billy.ohos.loadingstatusview.wrapability;

import com.billy.ohos.loadingstatusview.BaseAbility;
import com.billy.ohos.loadingstatusview.util.Util;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ShapeElement;

/**
 * demo: loading and load failed and click to retry
 *
 * @author billy.qi
 * @since 19/3/19 21:09
 */
public class GlobalFailedAbility extends BaseAbility {

    private Image img;
    private String picUrl;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        img = new Image(this);
        ShapeElement element = new ShapeElement();
        element.setRgbColor(new RgbColor(45, 132, 194));
        img.setBackground(element);
        img.setLayoutConfig(new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT));
        contentLayout.addComponent(img);
        super.setUIContent(contentLayout);
        picUrl = Util.getErrorImage();
        loadData();
    }

    private void loadData() {
        showLoading();
        getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                Glide.with(GlobalFailedAbility.this)
                        .load(picUrl)
                        .listener(new RequestListener<Element>() {
                            @Override
                            public boolean onLoadFailed(GlideException exception, Object object, Target<Element> target, boolean boo) {
                                showLoadFailed();
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Element element, Object object, Target<Element> target, DataSource dataSource, boolean boo) {
                                showLoadSuccess();
                                return false;
                            }
                        })
                        .into(img);
            }
        }, 1000);
    }

    @Override
    protected void onLoadRetry() {
        picUrl = Util.getRandomImage1();
        loadData();
    }

}
